package com.cyan.app.workflow.activity.WHM;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.cyan.app.barcode.CaptureActivity;
import com.cyan.app.workflow.AppData;
import com.cyan.app.workflow.R;
import com.cyan.app.workflow.base.activity.BaseFragmentActivity;
import com.cyan.app.workflow.bean.BaseBean;
import com.cyan.app.workflow.common.HttpConfig;
import com.cyan.app.workflow.customview.ShowTipDialog;
import com.cyan.app.workflow.util.AppUtils;
import com.cyan.app.workflow.util.ClickUtil;
import com.cyan.app.workflow.util.network.CommHttpListener;
import com.cyan.app.workflow.util.network.GetRequestParams;
import com.cyan.app.workflow.util.network.VolleyUtil;
import com.android.volley.VolleyError;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by DXW on 2016-07-23.
 * 区域品号新增
 */
public class AreaItnbrNewActivity extends BaseFragmentActivity {

    public static final String TAG = "AreaItnbrNewActivity";
    private static final String FIXNR = "Area_Itnbr_New_fixnr";
    private Button mButtonFixnr; //库位
    private Button mButtonItnbr; //品号
    private Button mButtonSub;   //提交
    private EditText mEditTextFixnr;
    private EditText mEditTextItnbr;
    private EditText mEditTextOnhand1;
    private CheckBox mCheckBox;
    private ShowTipDialog showdialog = new ShowTipDialog();
    private String itnbr ="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.whm_area_itnbr_new);
        mEditTextFixnr= (EditText)findViewById(R.id.whm_area_itnbr_new_fixnr);
        initView();
        mEditTextItnbr= (EditText)findViewById(R.id.whm_area_itnbr_new_itnbr);
        mEditTextOnhand1= (EditText)findViewById(R.id.whm_area_itnbr_new_onhand1);
        mCheckBox = (CheckBox)findViewById(R.id.whm_area_itnbr_new_cb);

        mButtonFixnr = (Button)findViewById(R.id.whm_area_itnbr_new_fixnr_saoma);
        mButtonFixnr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(AreaItnbrNewActivity.this, CaptureActivity.class), 0x0001);
            }
        });

        mButtonItnbr = (Button)findViewById(R.id.whm_area_itnbr_new_itnbr_saoma);
        mButtonItnbr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(AreaItnbrNewActivity.this, CaptureActivity.class), 0x0002);
            }
        });
       /* AsyncLoader task = new AsyncLoader();
        task.execute("208", "C11160330300");*/
        //String manno =  this.getItnbrByManno("C11160330300");
        mButtonSub = (Button)findViewById(R.id.whm_area_itnbr_new_submit);
        mButtonSub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(ClickUtil.isFastClick(10)){
                    //20秒内不能重复操作
                    AppUtils.showTip(AreaItnbrNewActivity.this, "操作过于频繁。");
                    return;
                }
                String userId = AppData.getInstance().getUserId();
                if(userId.isEmpty()){
                    AppUtils.showTip(AreaItnbrNewActivity.this, "请先登录后再操作。");
                    return;
                }
                //验证品号是否存在
                if(mEditTextItnbr.getText().toString().isEmpty()){
                    AppUtils.showTip(AreaItnbrNewActivity.this, "品号不能为空。");
                }else if(mEditTextFixnr.getText().toString().isEmpty()){
                    AppUtils.showTip(AreaItnbrNewActivity.this, "库位不能为空。");
                }else if(mEditTextOnhand1.getText().toString().isEmpty()){
                    AppUtils.showTip(AreaItnbrNewActivity.this, "数量不能为空。");
                }else if(Integer.parseInt(mEditTextOnhand1.getText().toString())<=0){
                    AppUtils.showTip(AreaItnbrNewActivity.this, "数量必须大于0。");
                }else {//提交
                    try {
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("action", "319");
                        JSONArray array = new JSONArray();
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("Userno", userId);
                        jsonObject.put("OperationType","310");
                        JSONObject json = new JSONObject();
                        json.put("Itnbr", mEditTextItnbr.getText().toString());
                        json.put("Fixnr", mEditTextFixnr.getText().toString());
                        json.put("Onhand1", mEditTextOnhand1.getText().toString());
                        json.put("Onhand2", 0);
                        array.put(json);
                        jsonObject.put("ItnbrDetails",array);
                        params.put("params", jsonObject.toString());
                        VolleyUtil.sendStringRequestByGet(AreaItnbrNewActivity.this, HttpConfig.HTTP_MAIN_SERVER_URL, TAG, params, null, new CommHttpListener<Object>() {
                            @Override
                            public void onResponse(String result) {
                                super.onResponse(result);
                                if (result == null) {
                                    return;
                                }
                                BaseBean resultBean = new Gson().fromJson(result, BaseBean.class);

                                if (resultBean.getCode() == 1) {
                                    AppUtils.showTip(AreaItnbrNewActivity.this, "新增成功");
                                } else {
                                    AppUtils.showTip(AreaItnbrNewActivity.this, resultBean.getMsg());
                                }
                                if(!mCheckBox.isChecked()) {
                                    finish();
                                }else {
                                    mEditTextItnbr.setText("");
                                    //mEditTextFixnr.setText("");
                                    mEditTextOnhand1.setText("");
                                }
                            }

                            @Override
                            public void onCodeError(int code, String msg) {
                                AppUtils.showTip(AreaItnbrNewActivity.this, msg);
                            }

                            @Override
                            public void onVolleyError(VolleyError volleyError) {
                                AppUtils.showTip(AreaItnbrNewActivity.this, R.string.network_error);
                            }

                            @Override
                            public void onException(Exception e) {
                                AppUtils.showTip(AreaItnbrNewActivity.this, e.toString());
                            }
                        });

                    } catch (Exception e) {
                        e.printStackTrace();
                        AppUtils.showTip(AreaItnbrNewActivity.this, "执行失败，请联系IT人员");
                    }
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 0x0001 && resultCode == RESULT_OK) {
            String result = "";
            if(data != null) {
                result = data.getStringExtra("result");
            }
            if (!result.contains("10010")) {
                AppUtils.showTip(AreaItnbrNewActivity.this, "请扫描区域库位");
            }else{
                mEditTextFixnr.setText(String.valueOf(result.substring(9)));
                PreferenceManager.getDefaultSharedPreferences(this).edit().putString(FIXNR,result.substring(9)).commit();
            }
        }
        if(requestCode == 0x0002 && resultCode == RESULT_OK) {
            String result = "";
            if(data != null) {
                result = data.getStringExtra("result");
                AsyncLoader task = new AsyncLoader();
                task.execute("208", result);
            }
        }
    }

    //通过工单编号获取产品品号
    private  String getItnbrByManno(String manno){
        String result = null;
        try{
            JSONObject param = new JSONObject();
            param.put("Manno",manno );
            result= GetRequestParams.getRequestResult(HttpConfig.HTTP_MAIN_SERVER_URL, "208", param.toString(), getApplicationContext());
            if(!result.isEmpty()){
                return result;
            }
        }catch (Exception e){
            Log.e("error", e.toString());
        }

        return  result;
    }
    private void initView(){
        titleBar();
        String pross = PreferenceManager.getDefaultSharedPreferences(this).getString(FIXNR,null);
        if(pross!=null){
            mEditTextFixnr.setText(String.valueOf(pross));
        }
        //工单禁止键盘输入
        mEditTextFixnr.setInputType(InputType.TYPE_NULL);
    }
    private void titleBar(){
        TextView mTextView =(TextView)findViewById(R.id.top_title_info);
        mTextView.setText("添加库位品号");
        Button back = (Button) findViewById(R.id.top_title_back);
        back.getBackground().setAlpha(255);// 透明度0~255透明度值 ，值越小越透明
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //返回按钮
                finish();
            }
        });
    }

    public class AsyncLoader extends AsyncTask<String,Integer,String>
    {
        @Override
        protected void onPreExecute() {
            showdialog.showDialog(AreaItnbrNewActivity.this);
        }

        @Override
        protected String doInBackground(String... params) {
            String result = null;
            try{
                JSONObject param = new JSONObject();
                param.put("Manno", params[1]);
                result= GetRequestParams.getRequestResult(HttpConfig.HTTP_MAIN_SERVER_URL, params[0], param.toString(), getApplicationContext());
            }catch (Exception e){
                Log.e("error", e.toString());
            }
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            if (s == null||s.isEmpty()) {
                showdialog.closeDialog();
                return;
            }
            try {
               // CommonBean commonBean = new Gson().fromJson(s, CommonBean.class);
                JSONObject json = new JSONObject(s);
                if (!json.getString("Code").equals("1")) {
                    AppUtils.showTip(AreaItnbrNewActivity.this, json.getString("Msg"));
                } else {
                    String result = json.getString("Result");
                    JSONObject json1 = new JSONObject(result);
                    mEditTextItnbr.setText(json1.getString("itnbrf"));
                }
            }catch (Exception e){

            }
            showdialog.closeDialog();
        }
    }
}
